<?php
class Ynbusinesspages_Api_Core extends  Core_Api_Abstract {
	
	public function typeCreate($label) {
		$field = Engine_Api::_() -> fields() -> getField('1', 'ynbusinesspages_business');
		// Create new blank option
		$option = Engine_Api::_() -> fields() -> createOption('ynbusinesspages_business', $field, array('field_id' => $field -> field_id, 'label' => $label, ));
		// Get data
		$mapData = Engine_Api::_() -> fields() -> getFieldsMaps('ynbusinesspages_business');
		$metaData = Engine_Api::_() -> fields() -> getFieldsMeta('ynbusinesspages_business');
		$optionData = Engine_Api::_() -> fields() -> getFieldsOptions('ynbusinesspages_business');
		// Flush cache
		$mapData -> getTable() -> flushCache();
		$metaData -> getTable() -> flushCache();
		$optionData -> getTable() -> flushCache();

		return $option -> option_id;
	}
	
	public function getGateway($gateway_id)
	{
		return $this -> getPlugin($gateway_id) -> getGateway();
	}
	
	public function getPlugin($gateway_id)
	{
		if (null === $this -> _plugin)
		{
			if (null == ($gateway = Engine_Api::_() -> getItem('payment_gateway', $gateway_id)))
			{
				return null;
			}
			Engine_Loader::loadClass($gateway -> plugin);
			if (!class_exists($gateway -> plugin))
			{
				return null;
			}
			$class = str_replace('Payment', 'Ynbusinesspages', $gateway -> plugin);

			Engine_Loader::loadClass($class);
			if (!class_exists($class))
			{
				return null;
			}

			$plugin = new $class($gateway);
			if (!($plugin instanceof Engine_Payment_Plugin_Abstract))
			{
				throw new Engine_Exception(sprintf('Payment plugin "%1$s" must ' . 'implement Engine_Payment_Plugin_Abstract', $class));
			}
			$this -> _plugin = $plugin;
		}
		return $this -> _plugin;
	}
	
	public function checkYouNetPlugin($name) {
		$table = Engine_Api::_ ()->getDbTable ( 'modules', 'core' );
		$select = $table->select ()->where ( 'name = ?', $name )->where ( 'enabled  = 1' );
		$result = $table->fetchRow ( $select );
		if ($result) {
			return true;
		} else {
			return false;
		}
	}
    
    public function subPhrase($string, $length = 0) {
        if (strlen ( $string ) <= $length)
            return $string;
        $pos = $length;
        for($i = $length - 1; $i >= 0; $i --) {
            if ($string [$i] == " ") {
                $pos = $i + 1;
                break;
            }
        }
        return substr ( $string, 0, $pos ) . "...";
    }
}
